package com.cloudalibabagateway11001.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: TODO
 * @Author zx
 * @Date 2024/12/3 19:15
 * @Version 1.0
 */
//@Component
@Slf4j
public class MyFilter implements Ordered, GlobalFilter {
    /**
     * 过滤器
     * @param exchange 可以拿到请求和响应
     * @param chain 网关过滤器 过滤器链
     * @return 是否放行
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String userName = exchange.getRequest().getQueryParams().getFirst("userName");
        log.info("userName: " + userName);
        if (userName == null){
            log.info("用户名不存在，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 优先级 加载过滤器的顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
